package  com.tomvian.tools
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.utils.getTimer;
	
	/**
	 * ...
	 * @author Thomas Vian
	 */
	public class FPSDisplay extends Bitmap 
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		private var _showOmniTickPercent:Boolean;
		private var _omniTickCount:uint;
		private var _omniTick:OmniTick;
		
		private var _bmd:BitmapData
		
		private var _overFramerate:Number;
		
		private var _timer : uint;
		private var _timerPrev : uint;
		
		private var _frames : uint;
		
		private var _fillRect1:Rectangle;
		private var _fillRect2:Rectangle;
		private var _fillRect3:Rectangle;
		
		//--------------------------------------------------------------------------
		//
		//  Getters / Setters
		//
		//--------------------------------------------------------------------------
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function FPSDisplay(showOmniTickPercent:Boolean = false) 
		{
			super(_bmd = new BitmapData(62, 8, true, 0xFFFFFFFF));
			
			_showOmniTickPercent = showOmniTickPercent;
			_omniTick = OmniTick.tick;
			
			_fillRect1 = new Rectangle(1, 1, 60, 6);
			
			if (_showOmniTickPercent)
			{
				_fillRect2 = new Rectangle(1, 1, 60, 3);
				_fillRect3 = new Rectangle(1, 4, 60, 3);
			}
			else
			{
				_fillRect2 = new Rectangle(1, 1, 60, 6);
			}
			
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}
		
		private function onAdded(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			
			_overFramerate = 1.0 / stage.frameRate;
			
			OmniTick.tick.onTick.add(update);
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		private function update():void 
		{
			_timer = getTimer();
			
			if (_showOmniTickPercent) _omniTickCount += _omniTick.tickTime;
		   
			if( _timer - 1000 > _timerPrev )
			{
				var overTimerDiff:Number = 1.0 / Number(_timer - _timerPrev);
				
				_fillRect2.width = 60 * _frames * _overFramerate * overTimerDiff * 1000.0;
				if (_fillRect2.width > 60) _fillRect2.width = 60;
				
				_bmd.fillRect(_fillRect1, 0);
				_bmd.fillRect(_fillRect2, 0xFFFF0000);
				
				if (_showOmniTickPercent)
				{
					_fillRect3.width = 60 * _omniTickCount * overTimerDiff;
					
					_bmd.fillRect(_fillRect3, 0xFF00FF00);
					
					_omniTickCount = 0;
				}
				
				_frames = 0; 
				_timerPrev = _timer;
			}
			
			_frames++;
		}
	}
}